<template>
  <view class="card m-10px">
    <view class="flex justify-between mb-10px">
      <label>书籍</label>
      <view></view>
    </view>
    <template v-for="(item,index) in bookList">
      <view class="flex items-center py-5px" @click="handlerBookItemClick(item)">
        <u-image :src="item.cover" class="mr-10px" height="30px" width="30px" radius="4px"/>
        <view class="flex-1">
          <light-match-text :text="item.name" :light-text="keyword || ''"/>
        </view>
      </view>
      <u-line v-if="index < (bookList.length - 1)"/>
    </template>
    <template v-if="compHasMore">
      <view @click="handlerLoadMoreClick">
        <u-loadmore :status="loadMoreStatus"/>
      </view>
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref,reactive,inject,watch,computed } from 'vue'
import type { Ref } from 'vue'
import { debounce } from '@/utils/debounce.js'
import LightMatchText from "@/components/lightMatchText.vue";
import type {Book} from "@/api/book";
import UImage from "@/uni_modules/uview-plus/components/u--image/u--image.vue";
import ULine from "@/uni_modules/uview-plus/components/u-line/u-line.vue";
import ULoadmore from "@/uni_modules/uview-plus/components/u-loadmore/u-loadmore.vue";
import {BookListParam, getBookList} from "@/api/book";

const keyword = inject<Ref<string> | null>('keyword')
watch(() => keyword,debounce((newVal: string | null, oldVal: string | null) => {
  // 调用搜索
  // console.log('keyword', newVal)
  fnGetBookList()
},20))
const bookList = ref<Book[]>([])
const pageParam = reactive<{
  pageSize: number
  pageNum: number
  total: number
}>({
  pageSize: 10,
  pageNum: 1,
  total: 0
})
const fnGetBookList = async (isPush?: boolean) => {
  const params: BookListParam = {
    pageNum: pageParam.pageNum,
    pageSize: pageParam.pageSize,
    linkName: keyword?.value || ''
  }
  const { data } = await getBookList(params)
  if(isPush){
    pageParam.total = data.total
    bookList.value.push(...data.records)
  }else{
    bookList.value = data.records
  }
}
// 是否有更多数据
const compHasMore = computed(() => {
  return pageParam.pageSize * pageParam.pageNum < pageParam.total
})
// 书籍列表项点击事件
const handlerBookItemClick = (item: Book) => {

}
// 加载更多数据状态
const loadMoreState = ref<boolean>(false)
// 加载更多组件状态值
const loadMoreStatus = computed(() => {
  return loadMoreState.value ? 'loading' : compHasMore.value ? 'loadmore' : 'nomore'
})
// 加载更多按钮点击事件
const handlerLoadMoreClick = () => {
  loadMoreState.value = true
  setTimeout(() => {
    loadMoreState.value = false
  },3000)
}
</script>

<style lang="scss">
</style>
